package com.copa.gameStore.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import com.copa.gameStore.client.UserClient;
import com.copa.gameStore.domain.Order;
import com.copa.gameStore.domain.OrderDetail;
import com.copa.gameStore.domain.User;
import com.copa.gameStore.enums.PayStatus;
import com.copa.gameStore.enums.RefundStatus;
import com.copa.gameStore.holder.LoginUserHolder;
import com.copa.gameStore.mapper.OrderDetailMapper;
import com.copa.gameStore.service.OrderDetailService;
import com.copa.gameStore.vo.CartVo;
import com.copa.gameStore.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ValidationException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author copa
 * @createDate 2022-09-27 17:58
 * @function
 */
@Service
public class OrderDetailServiceImpl implements OrderDetailService {

    @Resource
    private OrderDetailMapper orderDetailMapper;

    @Resource
    private LoginUserHolder loginUserHolder;

    @Override
    public List<OrderDetail> add(CartVo cartVo, Order order) {
        List<OrderDetail> orderDetailList = new ArrayList<>();
        AtomicInteger subNum = new AtomicInteger(1);
        cartVo.getCartGoodsVo().forEach(cart -> {
            OrderDetail orderDetail = new OrderDetail()
                    .setOrderSn(order.getOrderSn())
                    .setOrderSubSn(order.getOrderSn() + "-" +subNum.getAndIncrement())
                    .setRefundStatus(RefundStatus.NOT_REFUND.getStatus())
                    .setGameGoodsId(cart.getGameGoods().getId())
                    .setPrice(cart.getGameGoods().getPrice())
                    .setNum(cart.getNum());
            if (orderDetailMapper.insert(orderDetail) <= 0) {
                throw new RuntimeException();
            }
            orderDetailList.add(orderDetail);
        });
        return orderDetailList;
    }

    @Override
    public void refund(String orderSubSn) {
        Long userId = loginUserHolder.getUser().getId();
        OrderDetail orderDetail = Optional.ofNullable(orderDetailMapper.selectByOrderSubSn(
                orderSubSn, userId, PayStatus.PAY.getStatus(), RefundStatus.NOT_REFUND.getStatus()
        )).orElseThrow(() -> new ValidationException("该订单不能发起退款"));
        orderDetail.setRefundStatus(RefundStatus.REFUNDING.getStatus());
        if (orderDetailMapper.updateById(orderDetail) <= 0) {
            throw new RuntimeException();
        }
    }

    @Override
    public BigDecimal checkRefund(String orderSubSn, Integer refundStatus) {
        OrderDetail orderDetail = Optional.ofNullable(orderDetailMapper.selectByOrderSubSn(
                        orderSubSn, null, PayStatus.PAY.getStatus(), RefundStatus.REFUNDING.getStatus()
        )).orElseThrow(() -> new ValidationException("该订单不能发起退款"));
        orderDetail.setRefundStatus(refundStatus == RefundStatus.REFUNDED.getStatus()
                ? RefundStatus.REFUNDED.getStatus()
                : RefundStatus.NOT_REFUND.getStatus());
        if (refundStatus == RefundStatus.REFUNDED.getStatus()) {
            orderDetail.setRefundTime(LocalDateTime.now());
        }
        if (orderDetailMapper.updateById(orderDetail) <= 0) {
            throw new RuntimeException();
        }
        return refundStatus == RefundStatus.REFUNDED.getStatus()
                ? orderDetail.getPrice().multiply(BigDecimal.valueOf(orderDetail.getNum()))
                : new BigDecimal(-1);
    }
}
